import { Toast } from 'mint-ui';
(function () {
    // ==================== 平台 ===========================
    var isAndroid = false;
    var isIOS = false;

    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf('iphone') >= 0) {
        isIOS = true;
    }

    if (ua.indexOf('android') >= 0) {
        isAndroid = true;
    }

    // ==================== 事件 ===========================

    // 事件常量
    var EVENTS = {
        READY_EVENT: 'YzJSBridgeReady', // YzJSBridge对象准备就绪事件
        BACK_EVENT: 'back', // 物理返回键回退事件
        RESUME_EVENT: 'resume', // 后台切换前台恢复事件
        OPTION_MENU_EVENT: 'optionMenu', // 后台切换前台恢复事件
        NEW_ORDER_EVENT: 'newOrder', // 后台切换前台恢复事件
    };

    // 触发事件（方便app触发事件）
    function trigger(eventName) {
        var eventObj = document.createEvent('Events');
        eventObj.initEvent(eventName);
        document.dispatchEvent(eventObj);
    }

    // ==================== 接口 ===========================

    // YzJSBridge是否准备就绪
    // 监听ready事件
    document.addEventListener(EVENTS.READY_EVENT, function (e) {
        isJsBridgeReady = true;
    }, false);

    // native接口常量
    var APIS = {
      "SHARD_BY_SYSTEM": 'shardBySystem',
      "OPEN_APP": 'openApp', // 打开app
      "CHECK_API" : "checkApi", //检测接口
      "GET_USER_INFO" : "getUserInfo",    //获取登录用户信息
      "SEND_HTTP_REQUEST" : "sendHttpRequest",  //发送http请求
      "SELECT_PICTURE" : "selectPicture", //选择图片
      "TAKE_PICTURE" : "takePicture", //拍照
      "VIEW_PICTURE" : "viewPicture",  //预览图片
      "UPLOAD_PICTURE" : "uploadPicture", //上传图片
      "LOGOUT" : "logout",//退出登录
      "EXIT_APP":"exitApp", //退出app
      "DIAL" : "dial", //拨打电话
      "LOGIN" : "login", //跳转登录界面
      "SET_TITLE":"setTitle",//设置title
      "OPEN_WIFI":"openWifi",
      "SHOW_OPTION_MENU":'showOptionMenu',//显示右上角操作按钮
      "HIDE_OPTION_MENU":'hideOptionMenu',//隐藏右上角操作按钮
      "SET_OPTION_MENU":'setOptionMenu',//设置右上角操作按钮与SHOW_OPTION_MENU配合使用
      "PUSH_WINDOW":'pushWindow',//新窗口打开
      "POP_WINDOW":'popWindow',//关闭当前窗口
      "POP_TO":"popTo",//返回首页
      "SET_BACK_OPTION":"setBackOption",//设置back键控制方式
      "TEST_VOICE_BROADCAST":"testVoiceBroadcast",//试听语音播报
      "SCAN":"scan",//扫码
      "SAVE_PICTURE":"savePicture",//保存图片到本地
      "OPEN_AUTHV2":"authV2",//首页授权获取支付宝uid
      "GET_APP_VERSION":"getAppVersion",//获取当前app的版本号
      "UPGRADE_APP":"upgradeApp",//更新app
      "OPEN_DETECT_VOICE_RIGHT":"openDetectVoiceRight",//打开语音配置权限检测页  安卓专有
      "TRADE_PAY":"tradePay",//支付
      "SET_SERVER_URL":"setServerUrl",//设置服务地址  安卓专有
      "REMOVE_H5_SOURCE":"RemoveH5Source",//删除H5资源 安卓专有
      "RESET_ALL":"ResetAll",//重置所有 安卓专有
      "DOWNLOAD_H5_SOURCE":"downLoadH5Source",//下载H5资源 安卓专有
      "HIDE_SPLASH":"hideSplash",//关闭闪屏
      "GET_NEARBY_WIFI":"getNearbyWIFI",//获取附近wifi
      "START_BROADCAST":"startBroadcast",//开启广播
      "STOP_BROADCAST":"stopBroadcast",//关闭广播
      "UPDATE_NATIVE_PAGE":"updateNativePage",//刷新native页面
      "WRITE_LOG_TO_APP":"writeLogToApp",//写日志到app
      "GOTO_WALLET": "gotoWallet",//跳转到钱包
      "OPEN_NATIVEPAGE": "openNativePage", // 打开原生页面
      "ROUTER_BEFORE_EACH": "routerBeforeEach", // 跳转页面通知原生显示或者隐藏tabbar
    };

    // 检测jsbridge
    function loopCheckJsBirdge(callback) {
        if (isJsBridgeReady) {
            callback();
        }
        else {
            var intervalObj = null;
            intervalObj = window.setInterval(function () {
                if (isJsBridgeReady) {
                    window.clearInterval(intervalObj);
                    callback();
                }

            }, 100);
        }
    }

    // 调用native接口
    // 具体方法签名以及返回值，请前往RAP平台（http://10.200.41.131/workspace/myWorkspace.do?projectId=42#127）
    function call(apiName, data, callback) {
        // 处理缺省值
        if (!data) {
            data = {};
        }
        else {
            if (typeof data == 'function') {
                callback = data;
                data = {};
            }
            else if (data.toString() != '[object Object]') {
                alert('AppUtil.call:参数必须为json对象');
                return;
            }
        }
        if (!callback) {
            callback = function () {};
        }
        else {
            if (typeof callback != 'function') {
                alert('AppUtil.call:回调必须为函数');
                return;
            }
        }

        loopCheckJsBirdge(function () { // 检测jsbridge对象
            window.YzJSBridge.call(APIS.CHECK_API, {
                apiName: apiName
            }, function (checkResult) { // 检测接口是否实现
                var checkResultJSON = JSON.parse(checkResult);
                if (checkResultJSON.success.toString() == 'true') {
                    window.YzJSBridge.call(apiName, data, function (result) { // 解析返回数据为json
                        callback(JSON.parse(result));
                    });
                }
                else { // 接口未实现
                    //Toast('当前版本暂不支持使用该功能，请下载最新版本');
                }
            });
        });
    }

    function call2(apiName, data, callback) {
        // 处理缺省值
        if (!data) {
            data = {};
        }
        else {
            if (typeof data == 'function') {
                callback = data;
                data = {};
            }
            else if (data.toString() != '[object Object]') {
                alert('AppUtil.call:参数必须为json对象');
                return;
            }
        }
        if (!callback) {
            callback = function () {};
        }
        else {
            if (typeof callback != 'function') {
                alert('AppUtil.call:回调必须为函数');
                return;
            }
        }

        loopCheckJsBirdge(function () { // 检测jsbridge对象
            window.YzJSBridge.call(apiName, data, function (result) { // 解析返回数据为json
                callback(JSON.parse(result));
            });
        });
    }
    function checkNativeApi(apiName, callback) {
        loopCheckJsBirdge(function () { // 检测jsbridge对象
            callback&&callback();
            window.YzJSBridge.call(APIS.CHECK_API, {
                apiName: apiName
            }, function (checkResult) { // 检测接口是否实现
                var checkResultJSON = JSON.parse(checkResult);
                if (checkResultJSON.success.toString() == 'true') {
                    callback&&callback();
                }
            });
        });
    }
    // 暴露到全局
    window.AppUtil = {};
    window.AppUtil.device = {isAndroid: isAndroid, isIOS: isIOS};

    window.AppUtil.EVENTS = EVENTS;
    window.AppUtil.trigger = trigger;

    window.AppUtil.APIS = APIS;
    window.AppUtil.call = call;
    window.AppUtil.call2 = call2;
    window.AppUtil.checkNativeApi = checkNativeApi;
    setTimeout(() => {
        if(window.selfControlBack){
            window.AppUtil.call(window.AppUtil.APIS.SET_BACK_OPTION, {
                control: true
            });
        }
    }, 2000);
})();
